/*
 * DestroyEmitter.h
 *
 *  Created on: 05.11.2012
 *      Author: caffeine
 */

#ifndef DESTROYEMITTER_H_
#define DESTROYEMITTER_H_
#include "DestroyListener.h"
#include <exception/OutOfBounds.h>

#include <irrArray.h>

class DestroyEmitter{
private:
	irr::core::array<DestroyListener*>*list;
public:
	void addListener(DestroyListener*listener){
		if (!list)
			list=new irr::core::array<DestroyListener*>();
		list->push_front(listener);
	}

	DestroyListener*getListener(irr::u32 index){
		if (!list)
			return 0;
		if (index>=list->size())
			GEN_OutOfBounds_ERROR("");
		return list[0][index];
	}

	irr::u32 getListenerCount(){
		if (!list)
			return 0;
		return list->size();
	}

	void removeListener(irr::u32 index){
		if (!list)
			return;
		list[0][index]->drop();
		list->erase(index);
		if (list->size()==0){
			delete list;
			list=0;
		}
	}

	void removeAllListener(){
		while (list && list->size()>0)
			removeListener(0);
	}

	void callDestoryEvent(){
		if (!list)
			return;
		for (irr::u32 i=0;i<list->size();i++)
			list[0][i]->onDestroy(this);
	}

	virtual ~DestroyEmitter(){
		callDestoryEvent();
	}
};


#endif /* DESTROYEMITTER_H_ */
